<template>
  <div class="upload-button">
    <button
        @click="handleClick"
        :disabled="isUploading"
        class="upload-btn"
    >
      <span v-if="!isUploading">打包并上传试卷</span>
      <span v-else>
        <i class="loading-icon"></i> 正在上传...
      </span>
    </button>
    <p v-if="uploadMessage" :class="['message', uploadStatus]">
      {{ uploadMessage }}
    </p>
  </div>
</template>

<script>
export default {
  name: 'UploadButton',
  props: {
    examId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      isUploading: false,
      uploadMessage: '',
      uploadStatus: '' // 'success' or 'error'
    }
  },
  methods: {
    async handleClick() {
      this.isUploading = true;
      this.uploadMessage = '';
      this.uploadStatus = '';

      try {
        // 触发父组件的upload事件
        this.$emit('upload', this.examId);
        this.uploadMessage = '上传命令已发送';
        this.uploadStatus = 'success';
      } catch (error) {
        this.uploadMessage = `上传失败: ${error.message}`;
        this.uploadStatus = 'error';
        console.error('上传错误:', error);
      } finally {
        this.isUploading = false;
      }
    }
  }
}
</script>

<style scoped>
.upload-button {
  margin-top: 20px;
  text-align: center;
}

.upload-btn {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.upload-btn:hover:not(:disabled) {
  background-color: #45a049;
}

.upload-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.loading-icon {
  display: inline-block;
  width: 12px;
  height: 12px;
  border: 2px solid rgba(255,255,255,0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
  margin-right: 8px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.message {
  margin-top: 10px;
  padding: 8px;
  border-radius: 4px;
}

.message.success {
  background-color: #dff0d8;
  color: #3c763d;
}

.message.error {
  background-color: #f2dede;
  color: #a94442;
}
</style>